package com.synjones.aamodule;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 原始图像数组转bmp
 * @ClassName Bytes2Bmp
 * @author zhaodianbo@Synjones
 * @date 2015-10-10 下午4:12:06
 *
 */
public class Bytes2Bmp {
	private final int dataOffset=0x436;
	private final int bmpWidth=104;//宽度需要是4的倍数，所以原宽度102需要增加2个字节补位的数据
	private final int bmpHeight=144; 
	private final int bmpRawLen=bmpWidth*bmpHeight;
	private final int bmpFileLen=bmpRawLen+dataOffset;
	private byte bmpImg[]=new byte[bmpFileLen];
	private Context mContext;
	
	
	public Bytes2Bmp(Context context){
		this.mContext=context;
		CopyBmpHead();
	}
	
	public Bitmap get8bitBitmap(byte data[]){
		genBmp(data);
		Bitmap bmpBitmap=BitmapFactory.decodeByteArray(bmpImg, 0, bmpImg.length);
		return bmpBitmap;
	}
	
	
    public void saveMyBitmap(String bitName,Bitmap mBitmap ) {
    	//System.out.println(sdDir);
    	FileOutputStream fOut = null;
    	writeByte2SdcardFile(getExternalPath()+"fpImgRaw", bmpImg);
    	try {
    		File sdDir = Environment.getExternalStorageDirectory();
    		String fullname=sdDir.getCanonicalPath()+bitName;
    		File f = new File(fullname);		        
    		f.createNewFile();	        	        
    		fOut = new FileOutputStream(f);	      
    		mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);	        
            fOut.flush();	     
            fOut.close();
    	 } catch (Exception e) {
            e.printStackTrace();
            //log.debug(e.getMessage());
        }
    }

	public static String getExternalPath(){
		try {
			String ExternalPath=Environment.getExternalStorageDirectory().getCanonicalPath()+"/";
			return ExternalPath;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


	public static boolean writeByte2SdcardFile(String fileName,byte write_byte[]){
		boolean ret=false;
		try{
			FileOutputStream fout = new FileOutputStream(fileName);
			fout.write(write_byte);
			fout.flush();
			fout.close();
			ret=true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return ret;
	}



	private void genBmp(byte data[]){
		int width=bmpWidth;
		int originalDataPos=0;
		int originalLen=102*144;
		
		for(int i=0;i<bmpRawLen;i+=width){
			System.arraycopy(data, originalLen-originalDataPos-102, bmpImg, dataOffset+i, 102);	
			bmpImg[dataOffset+i+102]=0;//每行补2个零，使得每行的长度是4的倍数
			bmpImg[dataOffset+i+103]=0;
			originalDataPos+=102;
		}	
		
	}
	
	
	//need file bmp102x144_8bit_Head.bin in /assets folder
	private boolean CopyBmpHead()
	{	
	 	InputStream inputStream = null; 
	 	AssetManager assetManager =  mContext.getAssets(); 
	 	try { 
	 		inputStream = assetManager.open("bmp102x144_8bit_Head.bin"); 
	 		//BmpHead=new byte[inputStream.available()];
	 		inputStream.read(bmpImg);	
	 		inputStream.close();
	 		//write2SdcardFile(Dbfilename,inDb);
	 	} catch (IOException e) { 
	 		//log.debug("copyDb() err "+ e.getMessage()); 
	 		return false;
	 	} 
	 	return true;		  
	}
	
	
	/*private  void writeBmpHead(OutputStream out,int width,int height) throws IOException {
		LittleEndianDataOutput out1 = new LittleEndianDataOutput(out);
		int rowSize = (width * 3 + 3) / 4 * 4;  // 3 bytes per pixel in RGB888, round up to multiple of 4
		int imageSize = rowSize * height;
		
		// BITMAPFILEHEADER
		out1.writeBytes(new byte[]{'B', 'M'});  // FileType
		out1.writeInt32(14 + 40 + imageSize);   // FileSize
		out1.writeInt16(0);                     // Reserved1
		out1.writeInt16(0);                     // Reserved2
		out1.writeInt32(14 + 40);               // BitmapOffset
		
		// BITMAPINFOHEADER
		out1.writeInt32(40);                        // Size
		out1.writeInt32(width);                     // Width
		out1.writeInt32(height);                    // Height
		out1.writeInt16(1);                         // Planes
		out1.writeInt16(8);                        // BitsPerPixel
		out1.writeInt32(0);                         // Compression
		out1.writeInt32(imageSize);                 // SizeOfBitmap
		out1.writeInt32(bmp.horizontalResolution);  // HorzResolution
		out1.writeInt32(bmp.verticalResolution);    // VertResolution
		out1.writeInt32(0);                         // ColorsUsed
		out1.writeInt32(0);                         // ColorsImportant
		
		// Image data
		byte[] row = new byte[rowSize];
		for (int y = height - 1; y >= 0; y--) {
			for (int x = 0; x < width; x++) {
				int color = image.getRgb888Pixel(x, y);
				row[x * 3 + 0] = (byte)(color >>>  0);  // Blue
				row[x * 3 + 1] = (byte)(color >>>  8);  // Green
				row[x * 3 + 2] = (byte)(color >>> 16);  // Red
			}
			out1.writeBytes(row);
		}
		
		out1.flush();
	}
	*/
}
